package main

import (
	"bufio"
	"github.com/1141520944/go-library/hjz/common"
	"github.com/spf13/cast"
	"io"
	"net"
	"os"
	"strings"
	"zinxLearn/pkg/zinx/znet"
)

func main() {
	var (
		conn net.Conn
		err  error
	)
	l := common.LoggerDefault("zinx_client.log", "./tqLogger")
	defer func() {
		if err != nil {
			l.Errorw("[client] err", err.Error())
		}
	}()
	conn, err = net.Dial("tcp", "127.0.0.1:8000")
	if err != nil {
		return
	}
	input := bufio.NewReader(os.Stdin)
	dp := znet.NewDataPack()
	for {
		readString, cErr := input.ReadString('\n')
		if cErr != nil {
			l.Errorw("[client.conn] input.readString", err.Error())
			continue
		}
		str := strings.Trim(readString, "\r\n")
		if strings.ToUpper(str) == "Q" { // 退出
			return
		}
		// 按照 ，分割实例
		split := strings.Split(str, ",")
		msg, err := dp.Pack(znet.NewMessage(cast.ToUint32(split[0]), []byte(split[1])))
		if err != nil {
			l.Errorw("[client.conn] dp.Pack", err.Error())
			return
		}
		_, cErr = conn.Write(msg)
		if cErr != nil {
			l.Errorw("[client.conn] conn.write", err.Error())
			continue
		}
		buf := make([]byte, dp.GetHeadLen())
		io.ReadFull(conn, buf)
		unPack, _ := dp.UnPack(buf)
		var data []byte // 解析data
		if unPack.GetDataLen() > 0 {
			data = make([]byte, unPack.GetDataLen())
			if _, err = io.ReadFull(conn, data); err != nil {
				return
			}
		}
		println("[server]call back : ", string(data))
	}
}
